package com.lottery.im.module.chat.ui;

import android.app.Activity;
import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.OnClick;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.fondesa.recyclerviewdivider.RecyclerViewDivider;
import com.lottery.im.R;
import com.lottery.im.base.BaseActivity;
import com.lottery.im.module.chat.adapter.SelectGroupMemberAdapter;
import com.lottery.im.module.chat.presenter.SelectBusinessCardPresenter;
import com.lottery.im.module.chat.view.SelectBusinessCardView;
import com.lottery.im.module.tim.model.GroupMemberProfile;
import com.lottery.im.module.tim.model.SectionGroupMemberInfo;
import com.tencent.imsdk.TIMGroupMemberInfo;
import com.tencent.imsdk.TIMGroupMemberRoleType;
import com.tencent.imsdk.TIMUserProfile;
import java.util.ArrayList;
import java.util.List;

/**
 * 选择需要发送的群成员名片
 */
public class SelectBusinessCardActivity extends BaseActivity<SelectBusinessCardPresenter> implements
    SelectBusinessCardView {

  private final static String IDENTIFY_KEY = "IDENTIFY_KEY";

  public static void create(Activity activity, String identify,int requestCode) {
    Intent intent = new Intent(activity, SelectBusinessCardActivity.class);
    intent.putExtra(IDENTIFY_KEY, identify);
    activity.startActivityForResult(intent,requestCode);
  }

  @BindView(R.id.tv_title) TextView mTvTitle;
  @BindView(R.id.list) RecyclerView mList;
  @BindView(R.id.btn_confirm) Button mBtnConfirm;

  private String mIdentify;
  private List<SectionGroupMemberInfo> mGroupMemberInfos;
  private SelectGroupMemberAdapter mAdapter;
  private ArrayList<String> mSelectIds = new ArrayList<>();

  public final static String SELECT_IDENTIFYS_KEY = "SELECT_IDENTIFYS_KEY";

  @Override protected int getLayoutResId() {
    return R.layout.activity_businesscard_select;
  }

  @Override protected void initPresenter() {
    presenter = new SelectBusinessCardPresenter(this, this, this);
    presenter.init();
  }

  @Override public void initView() {
    mTvTitle.setText("群成员");
    mIdentify = getIntent().getStringExtra(IDENTIFY_KEY);

    mGroupMemberInfos = new ArrayList<>();
    mList.setLayoutManager(new LinearLayoutManager(this));
    RecyclerViewDivider.with(mActivity)
        .color(ContextCompat.getColor(mActivity, R.color.windowBackground))
        .size((int) mActivity.getResources().getDimension(R.dimen.line_size))
        .hideLastDivider()
        .build()
        .addTo(mList);

    mAdapter = new SelectGroupMemberAdapter(mGroupMemberInfos,mSelectIds);
    mAdapter.setOnItemClickListener((adapter, view, position) -> setCheck(position));
    mList.setAdapter(mAdapter);
    presenter.getGroupMembers(mIdentify);
  }

  @OnClick({ R.id.iv_back, R.id.btn_confirm }) public void onViewClicked(View view) {
    switch (view.getId()) {
      case R.id.iv_back:
        finish();
        break;
      case R.id.btn_confirm:
        confirm();
        break;
    }
  }

  /**
   * 拉取那些非好友的成员资料
   * 由于tim返回群成员的信息是没有头像跟昵称的
   */
  private void getUsersProfile() {

    List<String> ids = new ArrayList<>();
    for (SectionGroupMemberInfo memberInfo : mGroupMemberInfos) {
      if (!memberInfo.isHeader && TextUtils.isEmpty((memberInfo.t).getAvatarUrl())) {
        ids.add((memberInfo.t).getIdentify());
      }
    }
    if (ids.size() > 0) presenter.getUsersProfile(ids);
  }

  /**
   * @param position 点击的position
   * 修改选择状态
   */
  private void setCheck(int position){
    if (mGroupMemberInfos.get(position).isHeader)return;
    if (mSelectIds.contains((mGroupMemberInfos.get(position).t).getIdentify())){
      mSelectIds.remove((mGroupMemberInfos.get(position).t).getIdentify());
    }else {
      mSelectIds.add((mGroupMemberInfos.get(position).t).getIdentify());
    }
    mAdapter.setSelectIds(mSelectIds,position);
    if (mSelectIds.size() > 0){
      mBtnConfirm.setEnabled(true);
    }else{
      mBtnConfirm.setEnabled(false);
    }
  }

  /**
   * 选择完成，确定发送
   */
  private void confirm(){
    Intent data = new Intent();
    data.putStringArrayListExtra(SELECT_IDENTIFYS_KEY,mSelectIds);
    setResult(Activity.RESULT_OK,data);
    finish();
  }

  @Override public void showMemberInfo(List<TIMGroupMemberInfo> timGroupMemberInfos) {
    mTvTitle.setText("群成员(" + timGroupMemberInfos.size() + ")");
    mGroupMemberInfos.clear();

    List<TIMGroupMemberInfo> infos1 = new ArrayList<>();
    List<TIMGroupMemberInfo> infos2 = new ArrayList<>();

    for (TIMGroupMemberInfo info : timGroupMemberInfos) {
      if (info.getRole() == TIMGroupMemberRoleType.Owner
          || info.getRole() == TIMGroupMemberRoleType.Admin) {
        infos1.add(info);
      } else {
        infos2.add(info);
      }
    }

    if (infos1.size() > 0) {
      SectionGroupMemberInfo groupMemberInfo = new SectionGroupMemberInfo(true, "群主、管理员");
      mGroupMemberInfos.add(groupMemberInfo);
      for (TIMGroupMemberInfo info : infos1) {
        SectionGroupMemberInfo memberInfo =
            new SectionGroupMemberInfo(new GroupMemberProfile(info));
        mGroupMemberInfos.add(memberInfo);
      }
    }

    if (infos2.size() > 0) {
      SectionGroupMemberInfo groupMemberInfo = new SectionGroupMemberInfo(true, "其他成员");
      mGroupMemberInfos.add(groupMemberInfo);
      for (TIMGroupMemberInfo info : infos2) {
        SectionGroupMemberInfo memberInfo =
            new SectionGroupMemberInfo(new GroupMemberProfile(info));
        mGroupMemberInfos.add(memberInfo);
      }
    }
    mAdapter.notifyDataSetChanged();
    getUsersProfile();
  }

  @Override public void refreshUsersProfile(List<TIMUserProfile> timUserProfiles) {
    for (int i = 0; i < mGroupMemberInfos.size(); i++) {
      if (!mGroupMemberInfos.get(i).isHeader) {
        for(TIMUserProfile userProfile : timUserProfiles){
          if ((mGroupMemberInfos.get(i).t).getIdentify().equals(userProfile.getIdentifier())){
            mGroupMemberInfos.get(i).t.setAvatarUrl(userProfile.getFaceUrl());
            mGroupMemberInfos.get(i).t.setName(userProfile.getNickName());
            mGroupMemberInfos.get(i).t.setNickName(userProfile.getNickName());
            break;
          }
        }
      }
    }
    mAdapter.notifyDataSetChanged();
  }

}
